package com.senbai.springlearning.redislearn;

import com.sun.deploy.util.StringUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class NioRedis {
    static ByteBuffer byteBuffer = ByteBuffer.allocate(512);
    static List<SocketChannel> socketChannelList = new ArrayList<>();

    public static void main(String args[]) throws IOException {
        List<Integer> a = new ArrayList<>();
        a.add(1);
        a.add(2);
        a.add(3);
        System.out.println(a.stream().collect(Collectors.toList()));
        String abc = String.join(",", a.stream().map(String::valueOf).collect(Collectors.toList()));
        System.out.println(abc);
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        SocketAddress socketAddress = new InetSocketAddress("127.0.0.1",6379);
        serverSocket.bind(socketAddress);
        serverSocket.configureBlocking(false);

        while (true) {
            SocketChannel socketClient = serverSocket.accept();
            if (null != socketClient) {
                System.out.println("-------connected------");
                socketClient.configureBlocking(false);
                socketChannelList.add(socketClient);
                System.out.println("socketlist size = " + socketChannelList.size());
            }


            for (SocketChannel socketChannel : socketChannelList) {
                int read = socketChannel.read(byteBuffer);
                if (read > 0) {
                    System.out.println("------read-------" + read);
                    byteBuffer.flip();
                    byte[] bs = new byte[read];
                    byteBuffer.get(bs);
                    String content = bs.toString();
                    System.out.println(content);
                    byteBuffer.flip();
                }
            }
        }
    }
}
